import re
from pathlib import Path
import json

def to_camel(text:str)->str:
    """将变量名转换成驼峰命名"""
    result = []
    result.append(text[0].lower())
    i=1
    while i<len(text):
        if text[i] in {" ","-","_"}:
            i+=1
            result.append(text[i].upper())
        else:
            result.append(text[i])
        i+=1
    return "".join(result)

def time_to_seconds(text:str)->float:
    """ 将类似【1d 22h 17m 46.656s】格式的时间转换成秒 """
    if text == "" or text is None:
        return 0
    seconds = 0
    for t in re.split("\s+", text):
        s = float(t[:-1])
        if t[-1]=="d":
            s*=24*60*60
        elif t[-1]=="h":
            s*=60*60
        elif t[-1]=="m":
            s*=60
        seconds+=s
    return seconds

def read_data(data_path:str):
    """ 读取数据 """
    path=Path(data_path)
    if path.exists():
        with open(data_path,"r",encoding="utf-8") as f:
            data = json.load(f)
    else:
        data={}
    return data

def save_data(data,save_path:str,sort_keys=False):
    """ 保存数据 """
    path=Path(save_path)
    path.parent.mkdir(parents=True,exist_ok=True)
    with open(save_path,"w",encoding="utf-8") as f:
        json.dump(data,f,ensure_ascii=False,indent=4,sort_keys=sort_keys)